DROP PROCEDURE [dbo].[pr3600]
----- Purpose: Khoa so ky ke toan
GO
CREATE  PROCEDURE [dbo].[pr3600] @DivisionID varchar(20), 
			@TranMonth as int,
			@TranYear as int,
			@BeginDate  as datetime,
			@EndDate as datetime	
 AS

Declare @Closing As Bit,
	@NextMonth 	TinyInt,
	@NextYear 	Smallint,
	@PeriodNum 	TinyInt,
	@MaxPeriod	Int 
	
	EXEC pr3590 @DivisionID, @TranMonth, @TranYear
	Select 	@PeriodNum = PeriodNum
	From	tb0001
	If @PeriodNum Is Null 
		Set @PeriodNum = 12

	Set @NextMonth = @TranMonth % @PeriodNum + 1
	Set @NextYear = @TranYear + @TranMonth/@PeriodNum

	Select  	@Closing = Closing
	From 	tb3557
	Where 	DivisionID = @DivisionID And TranMonth = @TranMonth And TranYear = @TranYear
		
	Select 	@MaxPeriod = Max(TranMonth + TranYear * 100)
 	From	tb3557
	Where	DivisionID = @DivisionID

	If  @Closing <> 1 
	Begin
				
		Update 	tb3557
		Set 	Closing = 1
		From 	tb3557
		Where 	DivisionID = @DivisionID And TranMonth =@TranMonth And TranYear = @TranYear

		IF	@MaxPeriod < (@NextMonth + @NextYear * 100)
		Begin
			Insert    	tb3557  (TranMonth,TranYear, DivisionID, Closing, BeginDate, EndDate) 
			Values(@NextMonth,@NextYear, @DivisionID,0, @BeginDate, @EndDate)

			If Exists (Select 1 From tb3500 Where DivisionID = @DivisionID)
			Begin
				Update tb3500
				Set 	TranMonth = @NextMonth,
					TranYear = @NextYear			
			End
		End	
	End


GO